package com.fs.console.yuezi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fs.common.pojo.CheckNote;
import com.fs.common.pojo.Health;
import com.fs.common.service.CheckNoteService;
import com.fs.common.vo.ReportVo;
import com.fs.common.vo.ScoreVo;
import com.fs.common.vo.WeekRecipesVo;
import com.fs.common.yzMapper.CheckNoteMapper;
import com.fs.console.base.enums.CodeEnum;
import com.fs.console.base.param.SysConstant;
import com.fs.console.base.service.BaseService;
import com.fs.console.base.utils.ApplicationUtils;
import com.fs.console.base.vo.Criteria;
import com.fs.console.base.vo.JsonResponse;
import com.fs.console.yuezi.vo.HistogramVo;
import com.fs.console.yuezi.vo.MainVo;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author DeveloperKK
 * @desc
 * @creationTime 2019-08-14 09:49
 * @projectName yuezi-menu
 * @packageName com.fs.console.yuezi.controller
 */
@Slf4j
@Controller
@RequestMapping("/console/main/rewrite")
public class MainController {

    @Autowired
    private CheckNoteMapper checkNoteMapper;

    @Autowired
    private BaseService baseService;

    @Autowired
    private CheckNoteService checkNoteService;

    /**
     * data:{
     *     info:{//基本信息
     *         maternalName:"",//产妇姓名
     *         roomNumber:"",//房间号
     *         maternalNation:"",//民族
     *         delivery_day:"",分娩日期
     *         feedType:"",喂养方式 0母乳 1奶粉
     *         maternalMobile:""产妇手机号
     *     },
     *     score:{},//柱状图数据
     *     report:{
     *         face:{ //面诊
     *             result:"",//检测结果描述
     *             mediaAddress:"" //图片路径
     *         },
     *         tongue:{}//舌诊
     *     }
     * }
     */
    @RequestMapping(value = "/getCheckResult",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "获取检查结果")
    @ApiParam("checkId")
    //@PassToken
    public JsonResponse getCheckResult(HttpServletRequest request,String checkId){
        try {
            if (StringUtils.isBlank(checkId)){
                throw new RuntimeException("checkId不能为空！");
            }
            CheckNote cn = checkNoteMapper.selectById(checkId);
            return JsonResponse.success(JSON.parse(JSON.toJSONString(assembleObject(cn))));
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
           return  JsonResponse.error(CodeEnum.EX999);
        }
    }





    /**
     * data: {
     *  "checkId": "",
     *  maternalName:"",//产妇姓名
     *  "report": "", //报告描述
     *  "highHealth": [], //体质分>=60
     *  "histograms": [{
     *   "name": "",
     *   "value": 0,
     *   "color": ""
     *  }],
     *  healthList[{
     *   name: "",
     *   represent: ""
     *  }]
     * }
     * @param request
     * @return
     */
    @RequestMapping(value = "/getCheckScore",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "获取最新检查成绩")
    //@PassToken
    public JsonResponse getCheckScore(HttpServletRequest request){
        try {
            List<CheckNote> list = getCheckNoteList();
            MainVo mainVo = null;
            if (list != null && list.size() >=1) {
                mainVo = parseCheckNoteScore(list.get(0));
            }
            return JsonResponse.success(JSON.parse(JSON.toJSONString(mainVo)));
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return  JsonResponse.error(CodeEnum.EX999);
        }
    }

    /**
     * 获取问卷历史记录
     * @return
     */
    @RequestMapping(value = "/getHisList",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "获取问卷历史记录")
    //@PassToken
    public JsonResponse getHisList(HttpServletRequest request){
        try {
            Map<String, Object> data = ApplicationUtils.getRequestDatas();
            QueryWrapper<Object> wrapper = new Criteria<Object>().addAuto(data);
            wrapper.eq("creater_id",ApplicationUtils.getUserId());
            wrapper.orderByDesc("create_time");
            IPage<CheckNote> page = baseService.page("com.fs.common.pojo.CheckNote",request,wrapper);
            List<JSONObject> jsonList = new ArrayList<>();
            for (CheckNote cn : page.getRecords()) {
                jsonList.add( assembleObject(cn));
            }
            return JsonResponse.success(JSON.parse(JSON.toJSONString(jsonList)));
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return  JsonResponse.error(CodeEnum.EX999);
        }
    }

    /**
     * 解析并组装结果集
     * @param cn
     * @return
     */
    private JSONObject assembleObject(CheckNote cn){
        MainVo mainVo = null;
        Map<String, ReportVo> rvMap= null;
        List<WeekRecipesVo> recipesVos = new ArrayList<>();
        if (cn != null) {
            mainVo = parseCheckNoteScore(cn);
            rvMap = checkNoteService.parseReport(cn);
            recipesVos = checkNoteService.getRecipes(cn.getCheckId());
        }
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("info",cn);
        jsonObj.put("score",mainVo);
        jsonObj.put("report",rvMap);
        jsonObj.put("recipesVos",recipesVos);
        return jsonObj;
    }
    /**
     * 获取检查记录表
     * @return
     * @return
     */
    private List<CheckNote> getCheckNoteList(){
        Map<String,Object> data =  ApplicationUtils.getRequestDatas();
        QueryWrapper<CheckNote> wrapper = new Criteria<CheckNote>().addAuto(data);
        wrapper.eq("creater_id",ApplicationUtils.getUserId());
        wrapper.orderByDesc("create_time");
        return checkNoteMapper.selectList(wrapper);
    }


    /**
     * 获取检测成绩集合
     * @param list
     * @return
     */
    private List<MainVo> parseCheckNoteScoreList(List<CheckNote> list){
        List<MainVo> mainList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (CheckNote cn : list) {
                //获取体检成绩结果
                MainVo mainVo = parseCheckNoteScore(cn);
                if (mainVo != null) {
                    mainList.add(mainVo);
                }
            }
        }
        return mainList;
    }

    /**
     * 获取单次结果集合
     * @param checkNote
     * @return
     */
    private MainVo parseCheckNoteScore(CheckNote checkNote){
        Integer checkResult = checkNote.getCheckResult();
        MainVo vo =  new MainVo();
        vo.setCheckResult(checkResult);
        if (checkResult != -1 && StringUtils.isNotBlank(checkNote.getCheckScore())) {
            ScoreVo score = JSON.parseObject(checkNote.getCheckScore(),ScoreVo.class);
            String pointContent = score.getPointContent();
            if (StringUtils.isNotBlank(pointContent)) {
                String[] points = pointContent.split(ScoreVo.CONTENT_SPLIT);
                List<HistogramVo> hvList = new ArrayList<>();
                List<String> highDis = new ArrayList<>();
                List<Health> healthList = new ArrayList<>();
                String resultContent =  score.getResultContent();
                for (String p : points) {
                    String[] pArr = p.split(ScoreVo.POINT_SPLIT);
                    String name = pArr[0];
                    double value = Double.valueOf(pArr[1]);
                    hvList.add(new HistogramVo(name,value));
                    //分数大于50特殊处理
                    if (value >= 50) {
                        highDis.add(name);
                        Health hel = SysConstant.HEALTH_NAME.get(name);
                        if (hel != null){
                            //体质详情
                            healthList.add(hel);
                        }
                    }
                }
                List<WeekRecipesVo> recipes = checkNoteService.getRecipes(checkNote.getCheckId());
                vo = new MainVo(checkNote.getCheckId(),checkNote.getMaternalName(),resultContent,highDis,hvList,healthList,recipes,checkResult,score.getAdvises(),score.getAvoid());
            }
        }
        return vo;
    }

}
